/*
 * Toedo
 * Copyright (C) 2009-2010 J. Devauchelle and contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package org.toedo.utils;

import java.io.File;

import org.eclipse.jface.util.Util;
import org.toedo.logging.Log;

public class SystemUtils {
	
	public static final String fileSeparator = System.getProperty("file.separator"); //$NON-NLS-1$
	public static final String applicationDirectory = getApplicationDirectory();
	
	public static final String recentlyUsedFilesListFile = applicationDirectory + fileSeparator + "recentlyusedlist.properties";
	
	/**
	 * Create default configuration content.
	 */
	public static void createConfiguration() {
		Log.getInstance(SystemUtils.class).info("Checking configuration."); //$NON-NLS-1$
		
		File appDir = new File(applicationDirectory);
		if (!appDir.exists()) {
			Log.getInstance(SystemUtils.class).info("Creating configuration directory."); //$NON-NLS-1$
			appDir.mkdir();
		}
	}
	
	private static String getApplicationDirectory() {
		String result = null;
		
		// Get the XDG_CONFIG_HOME environment variable
		String xdgConfigHomePath = System.getenv("XDG_CONFIG_HOME");  //$NON-NLS-1$
		
		if ((xdgConfigHomePath != null) &&
				(!xdgConfigHomePath.isEmpty())) {
			
			// If found, use it as the base path for the application directory.
			if (!xdgConfigHomePath.endsWith(fileSeparator)) {
				xdgConfigHomePath += fileSeparator;
			}

			result = xdgConfigHomePath + Constants.APP_NAME + fileSeparator;

		} else {
			// If XDG_CONFIG_HOME is not found, let's go to some default directory.
			if (Util.isWindows()) {
				// Under Windows, default base path for the application directory is
				// C:\Documents and Settings\<UserName>\Application Data
				result = System.getProperty("user.home") + fileSeparator + "Application Data" + fileSeparator + Constants.APP_NAME + fileSeparator; //$NON-NLS-1$ //$NON-NLS-2$

			} else {
				// Under other platform, default base path for the application directory is $HOME/.config, as specified by 
				// the FreeDesktop XDG folders specification (http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html)
				result = System.getProperty("user.home") + fileSeparator + ".config" + fileSeparator + Constants.APP_NAME + fileSeparator; //$NON-NLS-1$ //$NON-NLS-2$
			}
		}
		
		return result;
	}
}
